package com.iweb.education.student.Servlet;

import com.iweb.education.student.Service.StudentService;
import com.iweb.education.student.Service.StudentServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.util.List;
import java.util.Map;

@WebServlet("*.student")
public class StudentServlet extends HttpServlet {
    StudentService service = new StudentServiceImpl();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        String path = req.getServletPath();

        switch (path) {
            case "/login.student":
                login(req, resp);
                break;
            case "/personalInfo.student":
                showPersonalInfo(req, resp);
                break;
            case "/grades.student":
                showGrades(req, resp);
                break;
            case "/courseList.student":
                showCourseList(req, resp);
                break;
            case "/selectCourse.student":
                handleSelectCourse(req, resp);
                break;
            case "/dropCourse.student":
                handleDropCourse(req, resp);
                break;
            default:
                break;
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        doGet(req, resp);
    }

    private void showPersonalInfo(HttpServletRequest req, HttpServletResponse resp)
            throws IOException {
        HttpSession session = req.getSession();
        Integer sid = (Integer) session.getAttribute("sid");

        if (sid == null) {
            resp.sendRedirect(req.getContextPath() + "/index.html");
            return;
        }

        Map<String, Object> info = service.showPersonalInfo(sid);

        if (info != null) {
            resp.setContentType("text/html;charset=utf-8");
            StringBuilder html = new StringBuilder();
            html.append("<div class='student-info'>");
            html.append("<input type='hidden' name='sid' value='").append(info.get("sid")).append("'>");
            html.append("<input type='hidden' name='sname' value='").append(info.get("sname")).append("'>");
            html.append("<input type='hidden' name='ssex' value='").append(info.get("ssex")).append("'>");
            html.append("<input type='hidden' name='sphone' value='").append(info.get("sphone")).append("'>");
            html.append("<input type='hidden' name='sage' value='").append(info.get("sage")).append("'>");
            html.append("<input type='hidden' name='sadress' value='").append(info.get("sadress")).append("'>");
            html.append("</div>");

            resp.getWriter().write(html.toString());
        } else {
            resp.sendError(HttpServletResponse.SC_NOT_FOUND, "未找到学生信息");
        }
    }

    //登录
    private void login(HttpServletRequest req, HttpServletResponse resp)
            throws IOException {
        String sid = req.getParameter("username");
        String spassword = req.getParameter("password");

        if(sid != null && !"".equals(sid)) {
            try {
                Integer studentId = Integer.valueOf(sid);
                HttpSession session = req.getSession();

                if(service.isLogin(studentId, spassword, session)) {
                    session.setAttribute("sid", studentId);
                    resp.sendRedirect(req.getContextPath() + "/student/dashboard.html");
                } else {
                    resp.sendRedirect(req.getContextPath() + "/index.html?isLogin=0");
                }
            } catch(NumberFormatException e) {
                resp.sendRedirect(req.getContextPath() + "/index.html?isLogin=0");
            }
        } else {
            resp.sendRedirect(req.getContextPath() + "/index.html");
        }
    }
    //成绩查询
    private void showGrades(HttpServletRequest req, HttpServletResponse resp)
            throws IOException {
        HttpSession session = req.getSession();
        Integer sid = (Integer) session.getAttribute("sid");

        if (sid == null) {
            resp.sendRedirect(req.getContextPath() + "/index.html");
            return;
        }

        List<Map<String, Object>> grades = service.getGrades(sid);

        if (grades != null && !grades.isEmpty()) {
            resp.setContentType("text/html;charset=utf-8");
            StringBuilder html = new StringBuilder();
            html.append("<div class='grades-info'>");
            html.append("<table>");
            html.append("<tr><th>课程名称</th><th>学分</th><th>成绩</th><th>教师编号</th></tr>");

            for (Map<String, Object> grade : grades) {
                html.append("<tr>");
                html.append("<td>").append(grade.get("cname")).append("</td>");
                html.append("<td>").append(grade.get("cval")).append("</td>");
                html.append("<td>").append(grade.get("cmark")).append("</td>");
                html.append("<td>").append(grade.get("tid")).append("</td>");
                html.append("</tr>");
            }

            html.append("</table>");
            html.append("</div>");

            resp.getWriter().write(html.toString());
        } else {
            resp.sendError(HttpServletResponse.SC_NOT_FOUND, "未找到成绩信息");
        }
    }
    //选课查询
    private void showCourseList(HttpServletRequest req, HttpServletResponse resp)
            throws IOException {
        HttpSession session = req.getSession();
        Integer sid = (Integer) session.getAttribute("sid");

        if (sid == null) {
            resp.sendRedirect(req.getContextPath() + "/index.html");
            return;
        }

        List<Map<String, Object>> courses = service.getCourseList();
        resp.setContentType("text/html;charset=utf-8");
        StringBuilder html = new StringBuilder();
        html.append("<div class='course-list'>");
        html.append("<table>");
        html.append("<tr><th>课程编号</th><th>课程名称</th><th>上课时间</th><th>授课教师</th><th>学分</th><th>剩余容量</th><th>操作</th></tr>");

        for (Map<String, Object> course : courses) {
            Integer cid = (Integer) course.get("cid");
            boolean isSelected = service.isSelectedCourse(sid, cid);
            int cnumber = ((Number) course.get("cnumber")).intValue();

            html.append("<tr>");
            html.append("<td>").append(cid).append("</td>");
            html.append("<td>").append(course.get("cname")).append("</td>");
            html.append("<td>").append(course.get("ctime")).append("</td>");
            html.append("<td>").append(course.get("teachername")).append("</td>");
            html.append("<td>").append(course.get("cval")).append("</td>");
            html.append("<td class='cnumber-").append(cid).append("'>").append(cnumber).append("</td>");
            html.append("<td>");
            if (isSelected) {
                html.append("<button onclick='handleCourse(").append(cid)
                        .append(", false)' class='drop-btn'>退课</button>");
            } else if (cnumber > 0) {
                html.append("<button onclick='handleCourse(").append(cid)
                        .append(", true)' class='select-btn'>选课</button>");
            } else {
                html.append("<button disabled>已满</button>");
            }
            html.append("</td>");
            html.append("</tr>");
        }

        html.append("</table>");
        html.append("</div>");
        resp.getWriter().write(html.toString());
    }
    //选课的方法
    private void handleSelectCourse(HttpServletRequest req, HttpServletResponse resp)
            throws IOException {
        HttpSession session = req.getSession();
        Integer sid = (Integer) session.getAttribute("sid");
        Integer cid = Integer.valueOf(req.getParameter("cid"));

        resp.setContentType("application/json;charset=utf-8");
        if (service.selectCourse(sid, cid)) {
            resp.getWriter().write("{\"success\":true}");
        } else {
            resp.getWriter().write("{\"success\":false}");
        }
    }
    //退课的方法
    private void handleDropCourse(HttpServletRequest req, HttpServletResponse resp)
            throws IOException {
        HttpSession session = req.getSession();
        Integer sid = (Integer) session.getAttribute("sid");
        Integer cid = Integer.valueOf(req.getParameter("cid"));

        resp.setContentType("application/json;charset=utf-8");
        if (service.dropCourse(sid, cid)) {
            resp.getWriter().write("{\"success\":true}");
        } else {
            resp.getWriter().write("{\"success\":false}");
        }
    }
}
